<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\newagk\interfaces\AdminQuestionsServiceIf;
use com\gdl\newagk\dataobject\adminquestions\QuestionsDTO; 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * 试题后台接口
 * 包含列表 修改 添加 添加标签
 */
class api_AdminQuestionsService extends api_Abstract implements AdminQuestionsServiceIf{ 
    /**
     * 试题列表
     */
    public function questionsList(QuestionsDTO $ques)
    { 
        $where = $ques->where ? gdl_lib_BaseUtils::getStr($ques->where) : "";
        $offset = $ques->offset ? gdl_lib_BaseUtils::getStr($ques->offset) : "0";
        $num =  $ques->num ? gdl_lib_BaseUtils::getStr($ques->num, 'int') :10;
		$name = $ques->update ? gdl_lib_BaseUtils::getStr($ques->update) :"";
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		if($offset=='0') $offset=1;
		$rows = $num;
		$limit = ($offset - 1) * $rows . "," . $rows;
		$group = 'order by agk_questions.id desc limit '.$limit;		
		if(empty($where)){
			$result->message = "缺少必要参数";
			return $result;
		}
		if($name){
			$where.=" and (agk_questions.question like '%{$name}%' or agk_questions.id like '%{$name}%') ";	
		}
		
        try{
            $quesModel = new model_newagk_questions();
			$leftJoin = array('agk_qbank as qb'=>'agk_questions.qbankId=qb.id',
							'agk_sections as se'=>'agk_questions.sectionId=se.id', 
						);
			$filed ="agk_questions.id,agk_questions.typeId,agk_questions.question,agk_questions.select,agk_questions.status,qb.name,agk_questions.answer,agk_questions.describe,FROM_UNIXTIME(agk_questions.createTime, '%Y年%m月%d日') as update_time,se.seName,agk_questions.level,agk_questions.qbankId as platformName";
			$list = $quesModel->select($where,$filed, $group,'',$leftJoin)->items;
			$listCount = $quesModel->select($where,'count(agk_questions.id) as num', '','',$leftJoin)->items;
			$result->code =200;
			$result->datas[] = ['count'=>$listCount[0]['num']?$listCount[0]['num']:0];
			
			if($list){
				$qbankModel = new model_newagk_qbank();
				$platformModel = new model_newagk_platform();
				$drawquestion = new service_drawquestion();
				for($i=0; $i<count($list); $i++){
					$qbankPlaformId = $qbankModel->selectOne('id='.$list[$i]['platformName'],'id,platformId');
					$list[$i]['platformName'] = "总平台";
					if(!empty($qbankPlaformId['platformId']) && $qbankPlaformId['platformId']!=0){
						$platformName = $platformModel->selectOne('id='.$qbankPlaformId['platformId'], 'reals,adminRealname');
						$list[$i]['platformName'] = $platformName['reals'];
					}
					$list[$i]['question'] = $drawquestion->deleteHtml($list[$i]['question']);
				}
				$result->message = "获取成功";
				$result->data = $list;
				
			}else{
				$result->message = "暂无数据"; 
				$result->data = [];
			}
        } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage(); 
        }
        return $result; 
    }
	/**
	* 试题详情
	*/
	public function questionInfo(QuestionsDTO $ques){
		$id = $ques->id ? gdl_lib_BaseUtils::getStr($ques->id) : "";
		$notHtml = $ques->where ? gdl_lib_BaseUtils::getStr($ques->where) : "";
		$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
		if(empty($id)){
			$result->message = "请带入试题标识";
			return $result;
		}
		try{
			$quesModel = new model_newagk_questions();
			$qbankTagModel = new model_newagk_qbanktag();
			$qbankModel = new model_newagk_qbank();
			$filed ="*";// "id,typeId,qbankId,question,`select`,selectNumber,answer,describe,knowsName,sectionId,pid,level,quesTag,quesTagVal";
			$getInfo = $quesModel->selectOne("id=".$id,$filed);
			$res = [
				'id'=>$getInfo['id'],
				'typeId'=>$getInfo['typeId'],
				'qbankId'=>$getInfo['qbankId'],
				'question'=> $getInfo['question'],
				'select'=>$getInfo['select'],
				'selectNumber'=>$getInfo['selectNumber'],
				'answer'=>$getInfo['answer'],
				'describe'=>$getInfo['describe'],
				'knowsName'=>$getInfo['knowsName'],
				'sectionId'=>$getInfo['sectionId'],
				'pid'=>$getInfo['pid'],
				'level'=>$getInfo['level'],
				'quesTag'=>$getInfo['quesTag'],
				'quesTagVal'=>$getInfo['quesTagVal'],
				'status'=>$getInfo['status'],
			];
			
			#如果有图片进行分割
			$res['selectArray'] = "";
			if($notHtml=='all' && ($res['typeId']==1 || $res['typeId']==2 || $res['typeId']==3)){
				$drawquestion = new service_drawquestion();
				$res['selectArray'] = json_encode($drawquestion->deleteSelectHtml($res['select']));
				$res['question'] = strip_tags($res['question']);
			}
			# 查出上级题库名
			$qbankName = $qbankModel->selectOne('id='.$getInfo['qbankId'],'id,name');
			$res['qbankName'] = $qbankName['name']?$qbankName['name']:"未获取";
			# 查出章节
			$sectionModel = new model_newagk_sections();
			$sectionInfo = $sectionModel->selectOne('isdelete=0 and id='.$res['sectionId'], 'seName');
			$res['sectionName'] = $sectionInfo['seName']?$sectionInfo['seName']:"未选择默认章节";
			
			if($res){
				
				# 组装标签
				if($res['quesTag']){
					$inStr = explode(',',$res['quesTag']);
					$inArray = implode("','",$inStr);
					$tagWhere = "isdelete = 0 and type=1 and (id in ('{$inArray}') or pid in ('{$inArray}') )"; 
					$tag = $qbankTagModel->select($tagWhere,'id,pid,tagName')->items; 
					if($tag){
						$tagList = [];
						$tagValueList = [];
						$tagValue = explode(',',$res['quesTagVal']);
						
						for($i=0; $i<count($tag); $i++){
							if($tag[$i]['pid']==0){								
								$tagList[] = ['id'=>$tag[$i]['id'],'pid'=>0, 'pname'=>$tag[$i]['tagName']]; 
							}else{
								$_select = "no";
								if(in_array($tag[$i]['id'],$tagValue)){
									$_select = "select";
								}
								$tagValueList[] = ['id'=>$tag[$i]['id'],'pid'=>$tag[$i]['pid'], 'name'=>$tag[$i]['tagName'],'select'=>$_select]; ; 
							}
							
						}
						$res['quesTag'] = json_encode($tagList);
						$res['quesTagVal'] = json_encode($tagValueList);
					}
				}
				$result->code = 200;
				$result->message = "获取成功";
				$result->data[] = $res;
				
			}
		}catch(Exception $ex){
			$result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
		}
		return $result;
	}
    /**
     *  添加试题
     */
    public function addQuestion(QuestionsDTO $ques){ 
		$platformId = $ques->id ? gdl_lib_BaseUtils::getStr($ques->id) : "";
		$data = $ques->data ? $ques->data : "";		
		$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = []; 
		if(!is_array($data)){
			$result->message = "请填写正确的题库信息";
			return $result;
		}
		if(empty($data['qbankId'])){
			$result->message = "请选择题库";
			return $result;
		}
		
        try{
		 $quesModel = new model_newagk_questions();
		 $answerModel = new model_newagk_questionsanswer();
		 $qbankModel = new model_newagk_qbank();
		 # 查出上级题库相关信息
		 
		 $qbankInfo = $qbankModel->selectOne('isdelete=0 and status=1 and id='.$data['qbankId'], 'id,qbankPid,admin_reg,version');
		 $insertData = [
			'typeId'=>$data['typeId'],
			'qbankId'=>$data['qbankId'],
			'question'=>htmlspecialchars_decode($data['question']),
			'select'=>htmlspecialchars_decode($data['select']),
			'selectNumber'=>$data['selectNumber']?$data['selectNumber']:0,
			'answer'=>htmlspecialchars_decode($data['answer']),
			'describe'=>htmlspecialchars_decode($data['describe']),
			'knowsName'=>$data['knowsName'],
			'sectionId'=>$data['sectionId'],
			'createTime'=>time(), 
			'isdelete'=>0,
			'level'=>$data['level'],
			'qbankPid'=>$qbankInfo['qbankPid'] ? $qbankInfo['qbankPid']:0,#云题库id自己查
			'pid'=>0,
			'quesTag'=>$data['quesTag'],
			'quesTagVal'=>$data['quesTagVal'],
			'admin_id'=>1,
			'status'=>$data['status'],
			'admin_reg'=>$qbankInfo['admin_reg'] ? $qbankInfo['admin_reg'] : "", #上机题库的admin_reg 
		 ];
		 
		 $drawquestion = new service_drawquestion();
		 $answerList = $drawquestion->deleteHtml(htmlspecialchars_decode($data['select'])); 
		 # 添加试题
		 $_select = $drawquestion->exAnswerStrToArr($answerList);
		 $qid = $quesModel->insert($insertData);
		 # 插入答案
		 $answerFormat = '';
		 foreach ($_select as $kw => $aw) {
			//$_answerData[] = array(
			$_answerData = array(
				'questionsId' => $qid,
				'option' => $kw ? $kw : 'UNKOWN',
				'answer' => $aw ? $aw : 'UNKOWN'
			);
			//处理答案选项为标准格式
			$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($aw).' ' : $kw.'.'.trim($aw);													
			$answerRet = $answerModel->insert($_answerData);
		 }
		 if($qid){
			 # 修改版本号 和 题目数量
			$qbankCount = $quesModel->select('qbankId='.$data['qbankId'].' and isdelete=0 and status=1','count(id) as num')->items;
			$qbankUp = ['total'=>$qbankCount[0]['num'],'version'=>$qbankInfo['version']+1];
			$qbankUpdateIs = $qbankModel->update('id='.$data['qbankId'],$qbankUp);
			 $result->code = 200;
			 $result->message = "添加试题成功";
		 }
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
    /**
     *  修改试题
     */
    public function editQuestion(QuestionsDTO $ques){
        $id = $ques->id ? gdl_lib_BaseUtils::getStr($ques->id) : ""; # 试题id
		$data = $ques->data ? $ques->data : "";		# 需要修改的内容
		$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = []; 
		if(!is_array($data)){
			$result->message = "请填写正确的试题信息";
			return $result;
		}
		if(empty($data['qbankId'])){
			$result->message = "请选择题库";
			return $result;
		}
		if(empty($id)){
			$result->message = "请带入正确的试题标识";
			return $result;
		} 
        try{
			$quesModel = new model_newagk_questions();
			$answerModel = new model_newagk_questionsanswer();
			$qbankModel = new model_newagk_qbank();
			# 查出上级题库相关信息

			$qbankInfo = $qbankModel->selectOne('isdelete=0 and status=1 and id='.$data['qbankId'], 'id,qbankPid,admin_reg,version');
			$insertData = [
				'typeId'=>$data['typeId'],
				'qbankId'=>$data['qbankId'],
				'question'=>htmlspecialchars_decode($data['question']),
				'select'=>htmlspecialchars_decode($data['select']),
				'selectNumber'=>$data['selectNumber']?$data['selectNumber']:0,
				'answer'=>htmlspecialchars_decode($data['answer']),
				'describe'=>htmlspecialchars_decode($data['describe']),
				'knowsName'=>htmlspecialchars_decode($data['knowsName']),
				'sectionId'=>$data['sectionId'],
				'level'=>$data['level'],
				'quesTag'=>$data['quesTag'],
				'quesTagVal'=>$data['quesTagVal'],
				'status'=>$data['status']
			]; 
			# 先修改
			$condition = "id=".$id;
			$upRet = $quesModel->update($condition,$insertData);
			if($upRet){
				#删了答案，重新插入
				$deleteQues = $quesModel->delete('piquestionsId='.$id);
				$drawquestion = new service_drawquestion();
				$answerList = $drawquestion->deleteHtml(htmlspecialchars_decode($data['select'])); 
				# 添加试题
				$_select = $drawquestion->exAnswerStrToArr($answerList); 
				# 插入答案
				$answerFormat = '';
				foreach ($_select as $kw => $aw) {
					$_answerData = array(
						'questionsId' => $id,
						'option' => $kw ? $kw : 'UNKOWN',
						'answer' => $aw ? $aw : 'UNKOWN'
					);
					//处理答案选项为标准格式
					$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($aw).' ' : $kw.'.'.trim($aw);													
					$answerRet = $answerModel->insert($_answerData);
				}
				# 修改版本号 和 题目数量
				$qbankCount = $quesModel->select('qbankId='.$data['qbankId'].' and isdelete=0 and status=1','count(id) as num')->items;
				$qbankUp = ['total'=>$qbankCount[0]['num'],'version'=>$qbankInfo['version']+1];
				$qbankUpdateIs = $qbankModel->update('id='.$data['qbankId'],$qbankUp);
				//if($qbankUpdateIs){
					$result->code = 200;
					$result->message = "修改成功";
				//} 
			}
			$result->code = 200;
			$result->message = "修改成功";
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
    /**
     *  添加标签
     */
    public function addTag(QuestionsDTO $ques){
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
        
		
        try{
           
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	
	/*
		切割答案
	*/
	public  function exAnswerStrToArr($str='',$delimiter='!@#'){
		$anIndex =  array('A','B','C','D','E','F','G');		
		//$str = 'A.中国##|B.胡天';
		//有分隔符的情况
		$resultArr = array();
		
		if(substr_count($str,$delimiter)>0) {
			$arr = explode($delimiter,$str);
			foreach($arr as $val){
				$arrTemp = self::exAnswerStrToArrReg($val);					
				$resultArr = array_merge($resultArr,$arrTemp);				
			}			
		}
		//判断机制
		
		if(false=== self::selectAnswerPass($resultArr)) {$resultArr = self::exAnswerStrToArrReg($str);}
		return $resultArr;		
	}
	/**
	  切割答案
	*/
	public static function exAnswerStrToArrReg($str=''){
		$anIndex =  array('A','B','C','D','E','F','G');	

		//临时处理特殊符号，今后写好正则后取消
		$symbols = array('、','？');
		
		foreach($symbols as $val){
			$str = str_replace($val,'.',$str);
		}
		//无分隔的情况 有ABCDE加.的情况
		$arr =  preg_split('/([a-zA-Z]+\.)/',$str,-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
		$resultArr = array();
		$isKey = false; $skey='';
		foreach($arr as $val){
			if($isKey){$resultArr[$skey] = $val;$isKey = false;}
			$val = str_replace('.','',$val);
			$val = str_replace(PHP_EOL,'',$val);
			$val = trim($val);
			if(in_array($val,$anIndex)) {
				$isKey=true;
				$skey=$val;
			}			
		}
		return $resultArr;
	}
	/*
		切割答案
	*/
	public static function selectAnswerPass($arr){
		
		if(empty($arr)) return false;
		$anIndex =  array('A','B','C','D','E','F','G');		
		$countKey=0;
		$arrKey = array_keys($arr);
		
		foreach($arrKey as $val){
			if(in_array($val,$anIndex)) $countKey++;
		}
		return $countKey<=1 ? false :true;
	}
   
}
